﻿// 公务用车信息管理
function BCarSend() {

    var BCarSendFields = new Array(
        { name: 'Id', type: 'string' },
        { name: 'ApplicantID', type: 'string' },
        { name: 'Applicant', type: 'string' },
        { name: 'ApplyDate', type: 'string' },
        { name: 'BCar' },
        { name: 'BCarNo', type: 'string' },
        { name: 'DriverID', type: 'string' },
        { name: 'Driver', type: 'string' },
        { name: 'ApplyFor', type: 'string' },
        { name: 'Type', type: 'string' },
        { name: 'PlanLine', type: 'string' },
        { name: 'MileBeg', type: 'string' },
        { name: 'MileEnd', type: 'string' },
        { name: 'Mileage', type: 'string' },
        { name: 'ExpOutTime', type: 'string' },
        { name: 'ExpInTime', type: 'string' },
        { name: 'ActOutTime', type: 'string' },
        { name: 'ActInTime', type: 'string' },
        { name: 'TT_ContUs', type: 'string' },
        { name: 'TT_ContIDD', type: 'string' },
        { name: 'TT_CustCarNo', type: 'string' },
        { name: 'TT_State', type: 'string' },
        { name: 'TT_Reason', type: 'string' },
        { name: 'TT_Fee', type: 'string' },
        { name: 'Description', type: 'string' }
    );

    // 定义filters
    var filters = new Ext.ux.grid.GridFilters({
        encode: true,
        filters: [{
            dataIndex: 'Brand', // 品牌
            options: ['丰田', '大众', '本田'],
            //options : DeptStore.collect('Name'),
            type: 'list'
        }]
    });

    //查询语句
    filters.buildQuery = function (filters) {
        var p = {}, i, f, root, dataPrefix, key, tmp, len = filters.length;
        if (!this.encode) {
            for (i = 0; i < len; i++) {
                f = filters[i];
                root = [this.paramPrefix, '[', i, ']'].join('');
                p[root + '[field]'] = f.field;

                dataPrefix = root + '[data]';
                for (key in f.data) {
                    p[[dataPrefix, '[', key, ']'].join('')] = f.data[key];
                }
            }
        } else {
            tmp = [];
            for (i = 0; i < len; i++) {
                f = filters[i];
                tmp.push(Ext.apply({}, {
                    field: f.field
                }, f.data));
            }
            if (tmp.length > 0) {
                p[this.paramPrefix] = Ext.util.JSON.encode(tmp);
            }
        }
        return p;
    };

    // 机构Combo Store
    var DeptStore = new Ext.data.JsonStore({
        url: '/InfraHospUser/GetDeptList',
        root: 'data',
        totalProperty: 'total',
        id: 'Id',
        fields: [{
            name: 'Id',
            type: 'string'
        }, {
            name: 'Name',
            type: 'string'
        }, {
            name: 'Code',
            type: 'string'
        }]
    });

    DeptStore.load({
        callback: function (r) {
            filters.addFilter({
                type: 'list',
                dataIndex: 'CurrentDep',
                options: JsHelper.GetFilterListData(r, 'Code', 'Name')
            });
        }
    });

    // 字典Store
    var DictStore = function (dictCategory) {
        var dictionaryStore = new Ext.data.JsonStore({
            url: '/InfraDictionary/GetPlistByCategoryCode?Code=' + dictCategory,
            root: 'data',
            totalProperty: 'total',
            id: 'Code',
            fields: [{
                name: 'Id',
                type: 'string'
            }, {
                name: 'Name',
                type: 'string'
            }, {
                name: 'Code',
                type: 'string'
            }]
        });
        return dictionaryStore;
    }

    // 与筛选有关的字典dictstore
    var DictFilterStore = function (dictCategory, filters, text, value) {
        var dictStore = DictStore(dictCategory);
        dictStore.load({
            callback: function (r) {
                filters.addFilter({
                    type: 'list',
                    dataIndex: dictCategory,
                    options: JsHelper.GetFilterListData(r, value, text)
                });
            }
        });
        return dictStore;
    }

    // Deport Store
    var TDeportStore = DictFilterStore('TDeport', filters, 'Name', 'Name');
    // 用车类型
    var BCUStore = DictFilterStore('BCU', filters, 'Name', 'Name');

    // 定义表单 商品车信息Reader
    var BCarSendInfoFormReader = new Ext.data.JsonReader({
        root: 'data',
        fields: BCarSendFields
    });

    // 定义表格 商品车信息store
    var itemGridStore = new Ext.data.Store({
        url: "/BCarSend/GetPlistAll",
        remoteSort: true,
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'total',
            id: 'Id',
            fields: BCarSendFields
        }),
        listeners: {
            'remove': function (thiz, record, index) {
                Ext.Ajax.request({
                    url: '/BCarSend/Delete?Id=' + record.data.Id,
                    success: function (response, opts) {
                        var result = Ext.util.JSON.decode(response.responseText);
                        if (result.success == false) {
                            JsHelper.ShowError(result.msg);
                            itemGridStore.insert(0, record);
                        }
                    }
                });
            }
        }
    });
    itemGridStore.setDefaultSort('CreateTime', 'ASC'); // 设置默认排序

    // 定义表格选择方式
    var sm = new Ext.grid.CheckboxSelectionModel();

    // 定义Grid表格列
    var cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), sm, {
        header: "申请日期",
        dataIndex: 'ApplyDate',
        xtype: 'datecolumn',
        format: 'Y年m月d日',
        sortable: true
    }, {
        header: "申请人",
        dataIndex: 'Applicant',
        sortable: true
    }, {
        header: "车牌号",
        dataIndex: 'BCarNo',
        sortable: true
    }, {
        header: "用车类型",
        dataIndex: 'Type',
        sortable: true
    }, {
        header: "审批人",
        dataIndex: 'AuthorUser',
        sortable: true
    }, {
        header: "司机",
        dataIndex: 'Driver',
        sortable: true
    }, {
        header: "用车事由",
        dataIndex: 'ApplyFor',
        sortable: true
    }, {
        header: "行驶里程",
        dataIndex: 'Mileage',
        sortable: true
    }, {
        header: "描述",
        dataIndex: 'Description'
    }]);

    //编辑窗口 todo.
    //var showEditFormWinFn2 = Fs.Car.CarForm(formReader, title, itemGridStore, id );


    // 定义表格工具栏
    var tbar = [{
        xtype: "tbbutton",
        minWidth: 80,
        ref: '../addBtn',
        text: "添加项",
        cls: "x-btn-text-icon",
        icon: "/Content/icons/add.png",
        handler: function (btn, e) {
            showBCarSendEditFormWinFn(BCarSendInfoFormReader, "添加公务派车单");
            //Fs.Car.CarForm.showCarEditFormWinFn(CarInfoFormReader, "添加商品车信息", itemGridStore)
        }
    }, "-", {
        xtype: "tbbutton",
        ref: '../delBtn',
        minWidth: 80,
        disabled: true,
        text: "删除项",
        cls: "x-btn-text-icon",
        icon: "/Content/icons/delete.png",
        handler: function (btn, e) {
            JsHelper.DelConfirm(function (btn) {
                if (btn == 'yes') {
                    // gridEditor.stopEditing();
                    var s = grid.getSelectionModel().getSelections();
                    for (var i = 0, r; r = s[i]; i++) {
                        itemGridStore.remove(r);
                    }
                }
            });
        }
    }, "-", {
        xtype: "tbbutton",
        minWidth: 80,
        text: "双击修改项",
        cls: "x-btn-text-icon",
        icon: "/Content/icons/pencil.png",
        disabled: true
    }];
    
    // 分页工具栏
    var bbar = new Ext.PagingToolbar({
        displayInfo: true,
        emptyMsg: "没有数据显示",
        displayMsg: "{0}到{1}条，共{2}条",
        store: itemGridStore,
        pageSize: ALL_PAGESIZE_SETTING,
        plugins: [filters]
    });

    // 商品车信息维护表格
    var grid = new Ext.grid.GridPanel({
        enableColumnMove: false,
        sm: sm,
        cm: cm,
        plugins: [filters],
        stripeRows: true,
        frame: true,
        border: true,
        layout: "fit",
        store: itemGridStore,
        loadMask: true,
        tbar: tbar,
        bbar: bbar,
        listeners: {
            "rowdblclick": function (g, rowIndex, e) {
                var store = g.getStore()
                var id = store.getAt(rowIndex).get("Id");
                //alert("id is : " + id);
                showBCarSendEditFormWinFn(BCarSendInfoFormReader, "修改公务派车信息", id);
            }
        }
    });

    // 控制删除按钮
    grid.getSelectionModel().on('selectionchange', function (sm) {
        grid.delBtn.setDisabled(sm.getCount() < 1);
    });

    var showBCarSendEditFormWinFn = function (formReader, title, id) {

        var updateEdit = Ext.isDefined(id);

        // 定义获得表单初始加载数据的请求参数
        var formLoadArgs = (updateEdit) ? {
            url: '/BCarSend/GetById',
            params: {
                'Id': id
            },
            waitMsg: '数据加载中...'
        } : null;

        var UserStore = new Ext.data.JsonStore({
            url: '/InfraHospUser/GetPlist',
            root: 'data',
            totalProperty: 'total',
            id: 'Id',
            fields: [{
                name: 'Id',
                type: 'string'
            }, {
                name: 'Name',
                type: 'string'
            }, {
                name: 'Code',
                type: 'string'
            }]
        });

        // 授权用户
        var UserCombo = new Ext.ux.form.SuperBoxSelect({
            allowBlank: false,
            fieldLabel: '授权审批用户<span style="color: red;" >*</span>',
            emptyText: '请选择...',
            minChars: 0,
            hiddenName: 'TmpAuthorizeUsers',
            store: UserStore,
            mode: 'remote',
            displayField: 'Name',
            valueField: 'Id',
            forceSelection: true,
            typeAheadDelay: 10000,
            triggerAction: 'all',
            listWidth: 250,
            width: 430,
            pageSize: 10,
            tpl: new Ext.XTemplate(
					'<div class="x-grid3"><div><table>',
					'<thead class="x-grid3-header"><tr class="x-grid3-hd-row">',
					'<td class="x-grid3-hd x-grid3-cell x-grid3-hd-inner" style="width: 50px;color: blue;">编码</td>',
					'<td class="x-grid3-hd x-grid3-cell" style="width: 200px;color: blue;">用户名</td>',
					'</tr></thead><tbody>',
					'<tpl for=".">',
					'<tr class="x-combo-list-item">',
					'<td class="x-grid3-col x-grid3-cell"><div class="x-grid3-cell-inner"  style="font-size:12px;">{Code}</div></td>',
					'<td class="x-grid3-col x-grid3-cell"><div class="x-grid3-cell-inner"  style="font-size:12px;">{Name}</div></td>',
					'</tr>', '</tpl>', '</tbody></table></div></div>')
        });

        var firstColumn = [{
            fieldLabel: '申请日期',
            xtype: 'datefield',
            name: 'ApplyDate',
            width: 150,
            format: 'Y年m月d日'
        }, {
            fieldLabel: '申请人<span style="color: red;" >*</span>',
            xtype: 'idccombo',
            id: 'Applicant',
            hiddenName: 'ApplicantID',
            store: UserStore,
            width: 150,
            listWidth: 200
        }, {
            fieldLabel: '车辆<span style="color: red;" >*</span>',
            xtype: 'idccombo',
            id: 'BCarNo',
            store: UserStore,
            width: 150,
            listWidth: 200
        }, {
            fieldLabel: '审批人<span style="color: red;" >*</span>',
            xtype: 'idccombo',
            id: 'AuthorUser',
            hiddenName: 'AuthorUserID',
            store: UserStore,
            width: 150,
            listWidth: 200
        }, {
            fieldLabel: '用车类型<span style="color: red;" >*</span>',
            xtype: 'idccombo',
            id: 'Type',
            store: BCUStore,
            width: 150,
            listWidth: 200
        }];

        var secondColumn = [{
            fieldLabel: '预计出发',
            xtype: 'datefield',
            width: 150,
            name: 'ExpOutTime',
            value: new Date(),
            readOnly: true,
            //disabled: true,
            hideTrigger: true,
            format: 'Y-m-d H:i:s'
        }, {
            fieldLabel: '预计返回',
            xtype: 'datefield',
            width: 150,
            name: 'ExpInTime',
            value: new Date().add(Date.HOUR, 2),
            readOnly: true,
            //disabled: true,
            format: 'Y-m-d H:i:s'
        }, {
            fieldLabel: '实际出发',
            xtype: 'datefield',
            width: 150,
            name: 'ActOutTime',
            format: 'Y-m-d H:i:s'
        }, {
            fieldLabel: '实际返回',
            xtype: 'datefield',
            width: 150,
            name: 'ActInTime',
            format: 'Y-m-d H:i:s'
        }, {
            fieldLabel: '出发里程',
            width: 150,
            name: 'MileBeg'
        }, {
            fieldLabel: '返回里程',
            width: 150,
            name: 'MileEnd'
        }];

        //
        var singleColumn = [
        {
            xtype: 'fieldset',
            title: '拖车信息', // title, header, or checkboxToggle creates fieldset header
            autoHeight: true,
            //columnWidth: 0.5,
            checkboxToggle: true,
            collapsed: false, // fieldset initially collapsed
            //layout: 'anchor',
            labelAlign: 'right',
            labelWidth: 80,
            items: [{
                layout: 'column',
                items: [{
                    columnWidth: .5,
                    bodyStyle: 'padding:1px',
                    layout: 'form',
                    defaultType: 'textfield',
                    items: [{
                        xtype: 'textfield',
                        fieldLabel: '客户姓名',
                        name: 'TT_ContUs',
                        width: 150
                    }, {
                        xtype: 'idccombo',
                        fieldLabel: '拖车结果',
                        name: 'TT_State',
                        width: 150
                    }, {
                        xtype: 'textfield',
                        fieldLabel: '车牌',
                        name: 'TT_CustCarNo',
                        width: 150
                    }, {
                        xtype: 'textfield',
                        fieldLabel: '原因',
                        name: 'TT_Reason',
                        width: 150
                    }]
                }, {
                    columnWidth: .5,
                    bodyStyle: 'padding:1px',
                    layout: 'form',
                    defaultType: 'textfield',
                    items: [{
                        xtype: 'textfield',
                        fieldLabel: '联系电话',
                        name: 'TT_ContIDD',
                        width: 150
                    }, {
                        xtype: 'textfield',
                        fieldLabel: '费用',
                        name: 'TT_Fee',
                        width: 150
                    }]
                }]
            }]
        }, {
            xtype: 'textfield',
            fieldLabel: '计划行车路线',
            name: 'PlanLine',
            width: 430
        }, {
            xtype: 'textarea',
            fieldLabel: '用车事由',
            name: 'ApplyFor',
            height: 50,
            width: 430
        }];


        // 定义表单 头部固定为两列 末尾单独列 需要改变布局时再修改
        var form = new Ext.FormPanel({
            border: false,
            waitMsgTarget: true,
            labelWidth: 90, // 注意 使用时 如果有表单内组件有特殊标签名称长度很大 替换合适的标签长度
            frame: true,
            bodyStyle: 'padding:5px 5px 0',
            //reader: BCarSendInfoFormReader, // 注意 这是传入方法的 Ext.data.DataReader 类型
            // 这里的借用表格store的reader属性
            labelAlign: 'right',
            //defaultType: 'textfield',
            items: [{
                layout: 'column',
                items: [{
                    columnWidth: .5,
                    bodyStyle: 'padding:1px',
                    layout: 'form',
                    defaultType: 'textfield',
                    items: firstColumn
                }, {
                    columnWidth: .5,
                    bodyStyle: 'padding:1px',
                    layout: 'form',
                    defaultType: 'textfield',
                    items: secondColumn
                }]
            }, singleColumn],
            buttonAlign: 'center',
            buttons: [new Ext.ux.SubmitBtn({
                handler: function () {
                    if (form.getForm().isValid()) {
                        form.getForm().submit({
                            url: '/BCarSend/SaveOrUpdate',
                            params: {
                                'AuthorizeUsers': UserCombo.getValue(),
                                'Id': (updateEdit) ? id : ""
                            },
                            success: function (form, action) {
                                itemGridStore.setDefaultSort('CreateTime', 'DESC');
                                itemGridStore.load({// 刷新表格
                                    params: {
                                        start: 0,
                                        limit: ALL_PAGESIZE_SETTING
                                    }
                                });
                                win.destroy(); // 关闭窗口
                            },
                            failure: function (form, action) {
                                JsHelper.ShowError(action.result.msg);
                            }
                        }); // formSubmitArgs
                        // 引用之前定义的请求参数变量
                    }
                }
            }), new Ext.ux.CancelBtn({
                handler: function () {
                    win.destroy();
                }
            })]
        });
        // 定义显示窗口
        var win = new Ext.Window({
            title: title,
            iconCls: 'application_form',
            width: 600,
            resizable: false,
            constrain: true,
            autoHeight: true,
            modal: true,
            closeAction: 'close',
            plain: true,
            items: [form]
        });
        win.show();

        //设置值
        form.form.setValues = function (values) {
            if (Ext.isArray(values)) { // array of objects
                for (var i = 0, len = values.length; i < len; i++) {
                    var v = values[i];
                    var f = this.findField(v.id);
                    if (f) {
                        f.setValue(v.value);
                        if (this.trackResetOnLoad) {
                            f.originalValue = f.getValue();
                        }
                    }
                }
            } else { // object hash
                var field, id;
                for (id in values) {
                    if (id == "JobType" && values[id] == "") {
                        continue;
                    }
                    if (!Ext.isFunction(values[id]) && (field = this.findField(id))) {
                        field.setValue(values[id]);
                        if (this.trackResetOnLoad) {
                            field.originalValue = field.getValue();
                        }
                    }
                }
            }
            return this;
        }

        form.form.on('beforeSetafterLoad', function (data) {
            var OUsers = data["AuthorizeUsers"];
            var UsersLen = OUsers.length;
            if (UsersLen > 0) {
                for (var i = 0; i < UsersLen; i++) {
                    UserCombo.addItemBox(OUsers[i]["Id"], OUsers[i]["Name"], OUsers[i]["Name"]);
                }
            }
        });

        if (formLoadArgs) {
            form.load(formLoadArgs); // formLoadArgs 引用之前定义表单数据加载的请求参数变量
        }
    };


    // 加载
    JsHelper.ExtTabDoLayout(grid);
    itemGridStore.load({
        params: {
            start: 0,
            limit: ALL_PAGESIZE_SETTING
        }
    });
};

BCarSend();

